<template>
  <div>
    <Drawer
      width="35%"
      :title="title"
      placement="right"
      v-model:visible="visible"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <template #closeIcon>
        <arrow-left-outlined />
      </template>

      <Form :model="formState" ref="formRef">
        <TypographyTitle :level="5">授权应用套餐</TypographyTitle>
        <Row :gutter="48">
          <Col span="12">
            <FormItem label="应用" name="appId" :rules="[{ required: true, message: '请选择应用' }]"
              ><Select
                v-model:value="formState.appId"
                :options="appOpt"
                style="width: 200px"
                placeholder="请选择"
                @change="appChange"
              ></Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="套餐" name="packageIdList" :rules="[{ required: true, message: '请选择套餐' }]"
              ><Select
                v-model:value="formState.packageIdList"
                :options="packageOpt"
                style="width: 200px"
                :disabled="disabled"
                mode="multiple"
                placeholder="请选择"
                @change="packageChange"
              ></Select>
            </FormItem>
          </Col>
        </Row>

        <template v-if="isAuthorizable">
          <Divider />
          <TypographyTitle :level="5">授权企业</TypographyTitle>
          <Space
            v-for="(item, index) in formState.tenantAndTimeList"
            :key="item.id"
            style="display: flex; margin-bottom: 8px"
            align="baseline"
          >
            <FormItem
              :name="['tenantAndTimeList', index, 'tenantId']"
              label="企业"
              :rules="{
                required: true,
                message: '请选择授权企业',
              }"
            >
              <Select
                v-model:value="item.tenantId"
                :options="tenantOpt"
                style="width: 200px"
                placeholder="请选择"
                @change="(value) => checkRepeat(value, item)"
              ></Select>
            </FormItem>

            <FormItem
              label="截止时间"
              :name="['tenantAndTimeList', index, 'expireTime']"
              :rules="{
                required: true,
                message: '请选择截止时间',
              }"
            >
              <DatePicker
                v-model:value="item.expireTime"
                style="width: 240px"
                :disabled-date="disabledDate"
                :showToday="false"
                placeholder="请选择"
              />
            </FormItem>
            <MinusCircleOutlined @click="removeSight(item)" />
          </Space>
          <FormItem>
            <Button type="dashed" block @click="addSight">
              <PlusOutlined />
              添加授权企业
            </Button>
          </FormItem>
        </template>
      </Form>

      <template #footer>
        <Button style="margin-right: 8px" type="primary" @click="submit">提交</Button>
        <Button @click="onClose">取消</Button>
      </template>
    </Drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { ArrowLeftOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import {
  Row,
  Col,
  Form,
  FormItem,
  Button,
  Select,
  Drawer,
  DatePicker,
  Space,
  message,
  TypographyTitle,
  Divider,
} from 'ant-design-vue';
import {
  addAppAuth,
  getAlias,
  getBusinessAppOpt,
  getPackagesOpt,
} from '/@/api/tenant-mgmt/enterpriseAppAuth/enterpriseAppAuth';
import { AddAppAuthParams, TenantAndTimeList } from '/@/api/tenant-mgmt/enterpriseAppAuth/model/enterpriseAppAuthModel';
import dayjs, { Dayjs } from 'dayjs';
const visible = ref(false);
const formRef = ref();
const formState = ref({ tenantAndTimeList: [] as TenantAndTimeList[] } as AddAppAuthParams);
const tenantOpt = ref();
const appOpt = ref();
const packageOpt = ref();
const disabled = ref(true);
const isAuthorizable = ref(false);
const title = ref();
const disabledDate = (current: Dayjs) => {
  return (current && current < dayjs().endOf('day')) || current > dayjs('9999-12-31 23:59:59');
};
const openAddAuth = async () => {
  visible.value = true;
  disabled.value = true;
  title.value = '新增企业应用授权';
  isAuthorizable.value = false;
  formState.value.tenantAndTimeList = [];
  appOpt.value = await getBusinessAppOpt();
  tenantOpt.value = await getAlias();
};
const appChange = async (app) => {
  if (app) {
    disabled.value = false;
    isAuthorizable.value = false;
    formState.value.tenantAndTimeList = [];
    formState.value.packageIdList = [];
    packageOpt.value = await getPackagesOpt(app);
  }
};
const addSight = () => {
  formState.value.tenantAndTimeList.push({
    tenantId: undefined,
    expireTime: undefined,
    id: Date.now(),
  });
};
const packageChange = (packages) => {
  if (packages && packages.length != 0) {
    isAuthorizable.value = true;
    if (formState.value.tenantAndTimeList.length == 0) {
      addSight();
    }
  } else {
    isAuthorizable.value = false;
    formState.value.tenantAndTimeList = [];
  }
};
const removeSight = (item: TenantAndTimeList) => {
  let index = formState.value.tenantAndTimeList.indexOf(item);
  if (index !== -1) {
    formState.value.tenantAndTimeList.splice(index, 1);
  }
};
const checkRepeat = (value, item) => {
  let arr = [];
  if (value && formState.value.tenantAndTimeList.length !== 1) {
    arr = [...formState.value.tenantAndTimeList];
    arr.pop();
    arr.forEach((it) => {
      if (value == it.tenantId) {
        message.warning('请勿给同一企业重复授权');
        removeSight(item);
      }
    });
  }
};
const onClose = () => {
  formState.value = {} as AddAppAuthParams;
  formRef.value.clearValidate();
  visible.value = false;
};
const emit = defineEmits(['get']);
const submit = () => {
  let tenantAndTimeList = [];
  formRef.value.validate().then(async () => {
    formState.value.tenantAndTimeList.forEach((item) => {
      tenantAndTimeList.push({
        tenantId: item.tenantId,
        expireTime: dayjs(item.expireTime).endOf('date').format('YYYY-MM-DD HH:mm:ss'),
      });
    });
    let params = {
      appId: formState.value.appId,
      packageIdList: formState.value.packageIdList,
      tenantAndTimeList,
    };
    let res = await addAppAuth(params);
    if (res) {
      message.success('授权成功');
    }
    emit('get');
    onClose();
  });
};
defineExpose({ openAddAuth });
</script>
